from typing import Optional
from asyncio import Queue
import os

# 弱用户名和弱密码字典文件路径
USERNAME_WORDLIST_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'docs', 'username.txt')
PASSWORD_WORDLIST_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'docs', 'password.txt')

# 全局变量，用于存储加载的弱用户名和弱密码集合
WEAK_USERNAMES = set()
WEAK_PASSWORDS = set()

def _load_wordlist(filepath: str) -> set:
    """加载字典文件到集合中。"""
    wordlist = set()
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            for line in f:
                word = line.strip()
                if word:
                    wordlist.add(word)
        print(f"[Weak Credential Detector] 成功加载 {len(wordlist)} 个词条从 {os.path.basename(filepath)}。")
    except FileNotFoundError:
        print(f"[Weak Credential Detector] 警告: 未找到字典文件: {filepath}。相关检测功能可能受限。")
    except Exception as e:
        print(f"[Weak Credential Detector] 警告: 加载字典文件 {filepath} 时发生错误: {e}。相关检测功能可能受限。")
    return wordlist

# 在模块加载时预加载字典
WEAK_USERNAMES = _load_wordlist(USERNAME_WORDLIST_PATH)
WEAK_PASSWORDS = _load_wordlist(PASSWORD_WORDLIST_PATH)

async def _send_status(status_queue: Optional[Queue], tool_name: str, message_type: str, data: dict):
    """辅助函数：向状态队列发送消息。"""
    if status_queue:
        await status_queue.put({
            "type": message_type,
            "step": tool_name,
            "data": data
        })

async def check_weak_credentials(username: str, password: str, status_queue: Optional[Queue] = None) -> dict:
    """
    检测给定的用户名和密码是否为弱凭证。
    """
    tool_name = "Weak_Credential_Detector"
    await _send_status(status_queue, tool_name, "tool_start", {"username": username, "password_len": len(password) if password else 0})

    is_weak_user = username in WEAK_USERNAMES
    is_weak_pass = password in WEAK_PASSWORDS

    reason = []
    if is_weak_user:
        reason.append(f"用户名 '{username}' 是常见弱用户名。")
    if is_weak_pass:
        reason.append(f"密码 '{password}' 是常见弱密码。")
    
    if not reason:
        reason.append("用户名和密码均未在弱字典中发现。")

    analysis_result = {
        "is_weak_username": is_weak_user,
        "is_weak_password": is_weak_pass,
        "is_weak_credential": is_weak_user or is_weak_pass,
        "reason": "; ".join(reason)
    }

    await _send_status(status_queue, tool_name, "tool_end", {"username": username, "result": analysis_result})
    return {"source": "Internal-Weak-Credential-Detector", "data": analysis_result, "status": "success"}
